package cn.geminis.workflow.service.service.model;

import cn.geminis.workflow.service.controller.vo.Task;
import cn.geminis.workflow.service.entity.repository.HistoricMapper;
import cn.geminis.workflow.service.utils.ObjectUtils;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.impl.cmd.AbstractCustomSqlExecution;
import org.springframework.stereotype.Service;

/**
 * @author puddi
 */
@Service
@RequiredArgsConstructor
public class ExtendDbOperateService {

    private final ProcessEngine engine;
    private final ApproveResultService approveResultService;

    public void updateDeleteReason(String taskId, String reason) {
        var execution = new AbstractCustomSqlExecution<HistoricMapper, Integer>(HistoricMapper.class) {
            @Override
            public Integer execute(HistoricMapper historicMapper) {
                historicMapper.updateTaskDeleteReason(taskId, reason);
                historicMapper.updateActivityDeleteReason(taskId, reason);
                return 1;
            }
        };
        this.engine.getManagementService().executeCustomSql(execution);
    }

    public Task getTask(String taskId) {
        var task = this.engine
                .getHistoryService()
                .createHistoricTaskInstanceQuery()
                .taskId(taskId)
                .singleResult();
        var taskVo = ObjectUtils.convert(task, Task.class);

        approveResultService.getByTaskInstanceId(taskId)
                .ifPresent(taskVo::setApproveResult);

        return taskVo;
    }
}
